﻿#region "Copyright (C) Lenny Granovsky. 2011-2013"
//    This library provides extended cache capabilities to the ASP.NET applications.
//
//                Copyright (C) Lenny Granovsky. 2011-2013. 
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 2 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
//    This program comes with ABSOLUTELY NO WARRANTY.
//    This is free software, and you are welcome to redistribute it
//    under certain conditions;
#endregion

using System;
using System.Diagnostics;
using System.Configuration;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Web.Caching;
using FlexiCache.Utilities;
//MongoDB driver by 10gen.
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using System.Text.RegularExpressions;

namespace FlexiCache
{
    /// <summary>
    /// Class provides functionality for out-of-process Cache based on Mongo DB. 
    /// It implements the OutputCacheProvider class. 
    /// </summary>
    /// <remarks>This class is not intended to be used directly.</remarks>
    public class MongoDBCacheStorageAdapter : CacheDataUtility, IDisposable, IExternalCacheStorageAdapter
    {
        private static Regex metadataRegex;

        static MongoDBCacheStorageAdapter()
        {
            metadataRegex = new Regex(@"([\\\.\*\/\[\]\(\)\{\}\^\+\?\$\=\!\<\>\|\:])", RegexOptions.Compiled | RegexOptions.CultureInvariant);
        }

        protected WriteConcern MongoWriteConcern
        {
            get
            {
                return this.IsAcknowledgedWrite ? WriteConcern.Acknowledged : WriteConcern.Unacknowledged;
            }
        }

        /// <summary>
        /// Default constructor.
        /// </summary>
        public MongoDBCacheStorageAdapter()
            : base()
        {
        }

        private MongoCollection<CacheItem> GetDBCollection()
        {
            MongoClient client = new MongoClient(this.DBConnectionString);
            MongoServer server = client.GetServer();
            MongoDatabase mongo = server.GetDatabase(this.CacheDatabaseName);

            MongoCollection<CacheItem> cacheItems = mongo.GetCollection<CacheItem>("CacheItem");
            return cacheItems;
        }

        public void ConnectionTest()
        {
            MongoClient client = null;
            MongoServer mongo = null;
            MongoCollection<CacheItem> cacheItems;
#if TRACE
            Stopwatch timer = new Stopwatch();
            timer.Start();
#endif
            client = new MongoClient(this.DBConnectionString);
            mongo = client.GetServer();
#if TRACE
            timer.Stop();
            Trace.TraceInformation(string.Format("{0}: Connected to Cache DB. Time: {1} ms.", this.TracePrefix, timer.Elapsed.TotalMilliseconds.ToString("F2")));
            timer.Restart();
#endif
            MongoDatabase store = mongo.GetDatabase(this.CacheDatabaseName);
            cacheItems = store.GetCollection<CacheItem>("CacheItem");
#if TRACE
            timer.Stop();
            Trace.TraceInformation(string.Format("{0}: Cache collection received. Time: {1} ms.", this.TracePrefix, timer.Elapsed.TotalMilliseconds.ToString("F2")));
#endif
            mongo = null;
        }

        /// <summary>
        /// Method gets a data from the cache using specified key.
        /// </summary>
        /// <param name="key">Data key.</param>
        /// <returns>Returns cached object.</returns>
        public object Get(string key)
        {
#if TRACE
            Stopwatch timer = new Stopwatch();
            timer.Start();
#endif
            object entry = null;
            try
            {
                string storedKey = ComputeCacheStorageKey(key);
                MongoCollection<CacheItem> cacheItems = this.GetDBCollection();

                CacheItem cacheItem = cacheItems.FindOne(Query.EQ("_id", storedKey));
#if TRACE
                timer.Stop();
                Trace.WriteLine(string.Format("{0}.Get({1}) find completed - item {2}. Time: {3} ms.", this.TracePrefix, key, (cacheItem == null) ? "is empty" : "exists", timer.Elapsed.TotalMilliseconds.ToString("F2")));
                timer.Restart();
#endif
                if (cacheItem != null)
                {
                    if (cacheItem.Expiration.ToUniversalTime() <= DateTime.UtcNow)
                    {
                        cacheItems.Remove(Query.EQ("_id", storedKey), this.MongoWriteConcern);
#if TRACE
                        timer.Stop();
                        Trace.WriteLine(string.Format("{0}.Get({1}) result: Cache Item removed as expired. Time: {2} ms.", this.TracePrefix, key, timer.Elapsed.TotalMilliseconds.ToString("F2")));
#endif
                    }
                    else
                    {
                        entry = Deserialize(cacheItem.Item);
#if TRACE
                        timer.Stop();
                        Trace.WriteLine(string.Format("{0}.Get({1}) result: Cache Item deserialized and ready. Time: {2} ms.", this.TracePrefix, key, timer.Elapsed.TotalMilliseconds.ToString("F2")));
#endif
                    }
                }
            }
            catch (Exception ex)
            {
#if TRACE
                timer.Stop();
                Trace.TraceError(string.Format("{0}.Get({1}) result: Exception: {2}.", this.TracePrefix, key, ErrorUtility.BuildFullExceptionMessage(ex)));
#endif
                base.HandleException(ex);
#if DEBUG
                throw;
#endif
            }

            return entry;
        }

        /// <summary>
        /// Method determines whether a cache entry for specified key exists in the cache.
        /// </summary>
        /// <param name="key">Data key.</param>
        /// <returns>Returns true if the cache contains a cache entry whose key matches key; otherwise, false.</returns>
        public bool Contains(string key)
        {
#if TRACE
            Stopwatch timer = new Stopwatch();
            timer.Start();
#endif
            try
            {
                string storedKey = ComputeCacheStorageKey(key);
                MongoCollection<CacheItem> cacheItems = this.GetDBCollection();

                MongoCursor<CacheItem> cacheItemCursor = cacheItems.Find(Query.EQ("_id", storedKey)).SetFields("_id");
#if TRACE
                timer.Stop();
                bool contains = (cacheItemCursor != null && cacheItemCursor.Count() > 0);
                Trace.WriteLine(string.Format("{0}.Get({1}) find completed - item {2}. Time: {3} ms.", this.TracePrefix, key, contains ? "exists" : "does not exist", timer.Elapsed.TotalMilliseconds.ToString("F2")));
#endif
                return contains;
            }
            catch (Exception ex)
            {
#if TRACE
                timer.Stop();
                Trace.TraceError(string.Format("{0}.Get({1}) result: Exception: {2}.", this.TracePrefix, key, ErrorUtility.BuildFullExceptionMessage(ex)));
#endif
                base.HandleException(ex);
#if DEBUG
                throw;
#endif
            }
#if !DEBUG
            return false;
#endif
        }

        /// <summary>
        /// Method adds data into the cache with specified key and expiration.
        /// </summary>
        /// <param name="key">Data key.</param>
        /// <param name="entry">Data to cache.</param>
        /// <param name="utcExpiry">Expiration time (UTC).</param>
        /// <param name="sessionId">The Session identifier, optional.</param>
        /// <returns>Returns cached object.</returns>
        public object Add(string key, object entry, DateTime utcExpiry, string sessionId)
        {
            return Add(key, entry, utcExpiry, sessionId, null);
        }

        /// <summary>
        /// Method adds data into the cache with specified key and expiration.
        /// </summary>
        /// <param name="key">Data key.</param>
        /// <param name="entry">Data to cache.</param>
        /// <param name="utcExpiry">Expiration time (UTC).</param>
        /// <param name="sessionId">The Session identifier, optional.</param>
        /// <param name="metaTags">The meta tags associated with the cached data, optional.</param>
        /// <returns>Returns cached object.</returns>
        public object Add(string key, object entry, DateTime utcExpiry, string sessionId, string[] metaTags)
        {
#if TRACE
            Stopwatch timer = new Stopwatch();
            timer.Start();
#endif
            if (entry == null) //remove data if null is to be added
            {
                this.Remove(key);
                return entry;
            }

            if (utcExpiry == DateTime.MaxValue)
                utcExpiry = DateTime.UtcNow.AddHours(5);

            try
            {
                string storedKey = ComputeCacheStorageKey(key);

                MongoCollection<CacheItem> cacheItems = this.GetDBCollection();
                CacheItem item = cacheItems.FindOne(Query.EQ("_id", storedKey));

                if (item != null)
                {
                    if (item.Expiration.ToUniversalTime() <= DateTime.UtcNow)
                        cacheItems.Remove(Query.EQ("_id", storedKey), this.MongoWriteConcern);
                    else
                    {
                        object tmp = Deserialize(item.Item);
#if TRACE
                        timer.Stop();
                        Trace.WriteLine(string.Format("{0}.Add({1}, {2}, {3}). (Existed) Time: {4} ms.", this.TracePrefix, key, entry, utcExpiry, timer.Elapsed.TotalMilliseconds.ToString("F2")));
#endif
                        return tmp;
                    }
                }
                byte[] data = Serialize(entry);
                if (this.MaxDataSizeLength > 0 && data.Length > this.MaxDataSizeLength)
                {
#if TRACE
                    timer.Stop();
                    Trace.TraceWarning(string.Format("{0}.Add({1}, {2}, {3}). Length: {4} bytes. (Overlimit) Time: {5} ms.", this.TracePrefix, key, entry, utcExpiry, data.LongLength.ToString(), timer.Elapsed.TotalMilliseconds.ToString("F2")));
#endif
                    return entry;
                }
                cacheItems.Insert<CacheItem>(new CacheItem
                {
                    Id = storedKey,
                    Item = data,
                    Expiration = utcExpiry,
                    SessionId = sessionId,
                    Metadata = base.BuildMetadata(metaTags)
                }, this.MongoWriteConcern);
#if TRACE
                timer.Stop();
                Trace.WriteLine(string.Format("{0}.Add({1}, {2}, {3}). Length: {4} bytes. (Inserted) Time: {5} ms.", this.TracePrefix, key, entry, utcExpiry, data.LongLength.ToString(), timer.Elapsed.TotalMilliseconds.ToString("F2")));
#endif
            }
            catch (WriteConcernException exSm)
            {
                if (exSm.Message.Contains("E11000 duplicate key error index"))
                {
#if TRACE
                    timer.Stop();
                    Trace.TraceError(string.Format("{0}.Add({1}, {2}, {3}). Duplicate Key collision detected: {4}.", this.TracePrefix, key, entry, utcExpiry, ErrorUtility.BuildFullExceptionMessage(exSm)));
#endif
                }
                else
                {
#if TRACE
                    timer.Stop();
                    Trace.TraceError(string.Format("{0}.Add({1}, {2}, {3}). Exception: {4}.", this.TracePrefix, key, entry, utcExpiry, ErrorUtility.BuildFullExceptionMessage(exSm)));
#endif
                    base.HandleException(exSm);
#if DEBUG
                    throw;
#endif
                }
            }
            catch (Exception ex)
            {
#if TRACE
                timer.Stop();
                Trace.TraceError(string.Format("{0}.Add({1}, {2}, {3}). Exception: {4}.", this.TracePrefix, key, entry, utcExpiry, ErrorUtility.BuildFullExceptionMessage(ex)));
#endif
                base.HandleException(ex);
#if DEBUG
                throw;
#endif
            }

            return entry;
        }

        /// <summary>
        /// Method sets (updates or adds) data into the cache with specified key and expiration.
        /// </summary>
        /// <param name="key">Data key.</param>
        /// <param name="entry">Data to cache.</param>
        /// <param name="utcExpiry">Expiration time (UTC).</param>
        /// <param name="sessionId">The Session identifier, optional.</param>
        /// <returns>Returns boolean value indicating success.</returns>
        public bool TrySet(string key, object entry, DateTime utcExpiry, string sessionId)
        {
            return TrySet(key, entry, utcExpiry, sessionId, null);
        }

        /// <summary>
        /// Method sets (updates or adds) data into the cache with specified key and expiration.
        /// </summary>
        /// <param name="key">Data key.</param>
        /// <param name="entry">Data to cache.</param>
        /// <param name="utcExpiry">Expiration time (UTC).</param>
        /// <param name="sessionId">The Session identifier, optional.</param>
        /// <param name="metaTags">The meta tags associated with the cached data, optional.</param>
        /// <returns>Returns boolean value indicating success.</returns>
        public bool TrySet(string key, object entry, DateTime utcExpiry, string sessionId, string[] metaTags)
        {
#if TRACE
            Stopwatch timer = new Stopwatch();
            timer.Start();
#endif
            if (entry == null) //remove data if null is to be set
            {
                this.Remove(key);
                return true;
            }

            try
            {
                string storedKey = ComputeCacheStorageKey(key);
                byte[] data = Serialize(entry);
                if (this.MaxDataSizeLength > 0 && data.Length > this.MaxDataSizeLength)
                {
#if TRACE
                    timer.Stop();
                    Trace.TraceWarning(string.Format("{0}.TrySet({1}, {2}, {3}). Length: {4} bytes. (Overlimit) Time: {5} ms.", this.TracePrefix, key, entry, utcExpiry, data.LongLength.ToString(), timer.Elapsed.TotalMilliseconds.ToString("F2")));
#endif
                    return false;
                }

                MongoCollection<CacheItem> cacheItems = this.GetDBCollection();
                CacheItem item = cacheItems.FindOne(Query.EQ("_id", storedKey));

                if (item != null)
                {
                    item.Item = data;
                    item.Expiration = utcExpiry;
                    cacheItems.Save(item, this.MongoWriteConcern);
                }
                else
                {
                    cacheItems.Insert(new CacheItem
                    {
                        Id = storedKey,
                        Item = data,
                        Expiration = utcExpiry,
                        SessionId = sessionId,
                        Metadata = base.BuildMetadata(metaTags)
                    }, this.MongoWriteConcern);
                }
#if TRACE
                timer.Stop();
                Trace.WriteLine(string.Format("{0}.TrySet({1}, {2}, {3}). Length: {4} bytes. Time: {5} ms.", this.TracePrefix, key, entry, utcExpiry, data.LongLength.ToString(), timer.Elapsed.TotalMilliseconds.ToString("F2")));
#endif
            }
            catch (WriteConcernException exSm)
            {
                if (exSm.Message.Contains("E11000 duplicate key error index"))
                {
#if TRACE
                    timer.Stop();
                    Trace.TraceError(string.Format("{0}.TrySet({1}, {2}, {3}). Duplicate Key collision detected: {4}.", this.TracePrefix, key, entry, utcExpiry, ErrorUtility.BuildFullExceptionMessage(exSm)));
#endif
                }
                else
                {
#if TRACE
                    timer.Stop();
                    Trace.TraceError(string.Format("{0}.TrySet({1}, {2}, {3}). Exception: {4}.", this.TracePrefix, key, entry, utcExpiry, ErrorUtility.BuildFullExceptionMessage(exSm)));
#endif
                    base.HandleException(exSm);
#if DEBUG
                    throw;
#endif
                }
            }
            catch (Exception ex)
            {
#if TRACE
                timer.Stop();
                Trace.TraceError(string.Format("{0}.TrySet({1}, {2}, {3}). Exception: {4}.", this.TracePrefix, key, entry, utcExpiry, ErrorUtility.BuildFullExceptionMessage(ex)));
#endif
                base.HandleException(ex);
#if DEBUG
                throw;
#endif
            }

            return true;
        }

        /// <summary>
        /// Method removes data from the cache using specified key.
        /// </summary>
        /// <param name="key">Data key.</param>
        public void Remove(string key)
        {
#if TRACE
            Stopwatch timer = new Stopwatch();
            timer.Start();
#endif

            try
            {
                string storedKey = ComputeCacheStorageKey(key);

                MongoCollection<CacheItem> cacheItems = this.GetDBCollection();
                cacheItems.Remove(Query.EQ("_id", storedKey), this.MongoWriteConcern);
#if TRACE
                timer.Stop();
                Trace.WriteLine(string.Format("{0}.Remove({1}). Time: {2} ms.", this.TracePrefix, key, timer.Elapsed.TotalMilliseconds.ToString("F2")));
#endif
            }
            catch (Exception ex)
            {
#if TRACE
                timer.Stop();
                Trace.TraceError(string.Format("{0}.Remove({1}). Exception: {2}.", this.TracePrefix, key, ErrorUtility.BuildFullExceptionMessage(ex)));
#endif
                base.HandleException(ex);
#if DEBUG
                throw;
#endif
            }
        }

        /// <summary>
        /// Method removes data from the cache using specified meta tags.
        /// </summary>
        /// <param name="metaTags">An array of meta tags.</param>
        public void Remove(string[] metaTags)
        {
#if TRACE
            Stopwatch timer = new Stopwatch();
            timer.Start();
#endif

            try
            {
                if (metaTags == null)
                    return;
                if (metaTags.Length == 0)
                    return;
                string metadataPattern = metadataRegex.Replace(string.Join("][", metaTags), "\\$1");
                metadataPattern = string.Format("\\[{0}\\]", metadataPattern.Replace("\\]\\[", "\\].*\\["));

                MongoCollection<CacheItem> cacheItems = this.GetDBCollection();
                cacheItems.Remove(Query.Matches("Metadata", new BsonRegularExpression(metadataPattern, "i")), this.MongoWriteConcern);
#if TRACE
                timer.Stop();
                Trace.WriteLine(string.Format("{0}.Remove[by meta tags]({1}). Time: {2} ms.", this.TracePrefix, base.BuildMetadata(metaTags), timer.Elapsed.TotalMilliseconds.ToString("F2")));
#endif
            }
            catch (Exception ex)
            {
#if TRACE
                timer.Stop();
                Trace.TraceError(string.Format("{0}.Remove[by meta tags]({1}). Exception: {2}.", this.TracePrefix, base.BuildMetadata(metaTags), ErrorUtility.BuildFullExceptionMessage(ex)));
#endif
                base.HandleException(ex);
#if DEBUG
                throw;
#endif
            }
        }

        /// <summary>
        /// Method gets the total count of records in the database instance.
        /// </summary>
        /// <returns>Returns the total count of records in the database instance.</returns>
        public long GetCount()
        {
#if TRACE
            Stopwatch timer = new Stopwatch();
            timer.Start();
#endif
            long cnt = 0;
            try
            {
                MongoCollection<CacheItem> cacheItems = this.GetDBCollection();
                cnt = cacheItems.Count();
#if TRACE
                timer.Stop();
                Trace.WriteLine(string.Format("{0}.GetCount(). Time: {1} ms.", this.TracePrefix, timer.Elapsed.TotalMilliseconds.ToString("F2")));
#endif
            }
            catch (Exception ex)
            {
#if TRACE
                timer.Stop();
                Trace.TraceError(string.Format("{0}.GetCount(). Exception: {1}.", this.TracePrefix, ErrorUtility.BuildFullExceptionMessage(ex)));
#endif
                base.HandleException(ex);
#if DEBUG
                throw;
#endif
            }

            return cnt;
        }

        /// <summary>
        /// Method removes all records from the database instance.
        /// </summary>
        public void RemoveAll()
        {
#if TRACE
            Stopwatch timer = new Stopwatch();
            timer.Start();
#endif
            try
            {
                MongoCollection<CacheItem> cacheItems = this.GetDBCollection();
                cacheItems.RemoveAll(this.MongoWriteConcern);
#if TRACE
                timer.Stop();
                Trace.WriteLine(string.Format("{0}.RemoveAll(). Time: {1} ms.", this.TracePrefix, timer.Elapsed.TotalMilliseconds.ToString("F2")));
#endif
            }
            catch (Exception ex)
            {
#if TRACE
                timer.Stop();
                Trace.TraceError(string.Format("{0}.RemoveAll(). Exception: {1}.", this.TracePrefix, ErrorUtility.BuildFullExceptionMessage(ex)));
#endif
                base.HandleException(ex);
#if DEBUG
                throw;
#endif
            }
        }

        /// <summary>
        /// Method removes all expired records from the database instance.
        /// </summary>
        public void RemoveExpired()
        {
#if TRACE
            Stopwatch timer = new Stopwatch();
            timer.Start();
#endif
            try
            {
                MongoCollection<CacheItem> cacheItems = this.GetDBCollection();
                cacheItems.Remove(Query.LTE("Expiration", DateTime.UtcNow), this.MongoWriteConcern);
#if TRACE
                timer.Stop();
                Trace.WriteLine(string.Format("{0}.RemoveExpired(). Time: {1} ms.", this.TracePrefix, timer.Elapsed.TotalMilliseconds.ToString("F2")));
#endif
            }
            catch (Exception ex)
            {
#if TRACE
                timer.Stop();
                Trace.TraceError(string.Format("{0}.RemoveExpired(). Exception: {1}.", this.TracePrefix, ErrorUtility.BuildFullExceptionMessage(ex)));
#endif
                base.HandleException(ex);
#if DEBUG
                throw;
#endif
            }
        }

        /// <summary>
        /// Method compacts data in the database.
        /// </summary>
        public void Compact()
        {//available in MongoDB v2.0
            //admin functionality - ignore for now
            //MongoDatabase mongo = null;
            try
            {
                //mongo = this.CreateDBInstance();
                //mongo.RunCommand("compact");
#if TRACE
                Trace.WriteLine(string.Format("{0}.Compact() - DB Name: {1}.", this.TracePrefix, this.CacheDatabaseName));
#endif
            }
            catch (Exception ex)
            {
#if TRACE
                Trace.TraceError(string.Format("{0}.Compact() - DB Name: {1}. Exception: {2}.", this.TracePrefix, this.CacheDatabaseName, ErrorUtility.BuildFullExceptionMessage(ex)));
#endif
                base.HandleException(ex);
#if DEBUG
                throw;
#endif
            }
        }

        /// <summary>
        /// Method updates the expiration date and time for specified item to renew it for next session timeout interval.
        /// </summary>
        public void Renew(string sessionId, DateTime utcExpiry)
        {
            try
            {
                MongoCollection<CacheItem> cacheItems = this.GetDBCollection();
                UpdateDocument update = new UpdateDocument { { "$set", new BsonDocument("Expiration", utcExpiry) } };

                cacheItems.Update(Query.EQ("SessionId", sessionId), update, UpdateFlags.Multi, this.MongoWriteConcern);
#if TRACE
                Trace.WriteLine(string.Format("SessionOnDemand.Renew({0}).", sessionId));
#endif
            }
            catch (Exception ex)
            {
#if TRACE
                Trace.TraceError(string.Format("SessionOnDemand.Renew({0}). Exception: {1}.", sessionId, ErrorUtility.BuildFullExceptionMessage(ex)));
#endif
                base.HandleException(ex);
#if DEBUG
                throw;
#endif
            }
        }

        /// <summary>
        /// Method removes all items associated with this session.
        /// </summary>
        public void Clear(string sessionId)
        {
            try
            {
                MongoCollection<CacheItem> cacheItems = this.GetDBCollection();
                cacheItems.Remove(Query.EQ("SessionId", sessionId), this.MongoWriteConcern);
#if TRACE
                Trace.WriteLine(string.Format("SessionOnDemand.Clear({0}).", sessionId));
#endif
            }
            catch (Exception ex)
            {
#if TRACE
                Trace.TraceError(string.Format("SessionOnDemand.Clear({0}). Exception: {1}.", sessionId, ErrorUtility.BuildFullExceptionMessage(ex)));
#endif
                base.HandleException(ex);
#if DEBUG
                throw;
#endif
            }
        }

        /// <summary>
        /// Method returns the list of items in the collection for this session.
        /// </summary>
        /// <remarks>This method is resource intensive and is designed for use by customer support. 
        /// Do not use from the application code.</remarks>
        /// <param name="includeActualData">Boolean value indicating where or not the actual data should be included or cleared.</param>
        /// <returns>Returns the list of items in the collection for this session.</returns>
        public List<CacheItemInfo> RetrieveCollection(string sessionId, bool includeActualData)
        {
            List<CacheItemInfo> result = null;
            try
            {
                MongoCollection<CacheItem> cacheItems = this.GetDBCollection();
                result = cacheItems.Find(Query.EQ("SessionId", sessionId)).ToList()
                    .Select<CacheItem, CacheItemInfo>(doc => new CacheItemInfo()
                    {
                        Id = doc.Id,
                        Item = includeActualData ? doc.Item : null,
                        DataLength = doc.DataLength
                    }).ToList();
#if TRACE
                Trace.WriteLine(string.Format("SessionOnDemand.RetrieveCollection({0}).", sessionId));
#endif
            }
            catch (Exception ex)
            {
#if TRACE
                Trace.TraceError(string.Format("SessionOnDemand.RetrieveCollection({0}). Exception: {1}.", sessionId, ErrorUtility.BuildFullExceptionMessage(ex)));
#endif
                base.HandleException(ex);
#if DEBUG
                throw;
#endif
            }
            return result;
        }

        public void Dispose()
        {
        }
    }
}
